package com.voodoo.lib_mqtt;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.ServiceUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Author：voodoo
 * CreateTime：2021/06/17 017 上午 09:31
 * Description：Mqtt服务的守护服务
 */
public class MqttGuardService extends Service {

    Timer timer;
    TimerTask timerTask;

    @Override
    public void onCreate() {
        super.onCreate();

        cancelTimer();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                checkedServicesLife();
            }
        };
        timer.schedule(timerTask, 60_000, 60_000);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 检查其他服务是否活着
     */
    private void checkedServicesLife() {
        boolean mqttServiceRunning = ServiceUtils.isServiceRunning(getApplicationContext(), MqttService.class.getName());
        L.i("Mqtt守护服务：Mqtt" + (!mqttServiceRunning ? "挂了" : "活着")); // 之所以反着来判断是为了直观的知道下面这部判断
        if (!mqttServiceRunning) {
            L.i("Mqtt守护服务：重新启动Mqtt");
            ServiceUtils.startService(getApplicationContext(), MqttService.class);
        }
    }

    private void cancelTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

}
